#!/usr/bin/python
# encoding:utf-8
import os
import json
import urllib.request
import urllib.parse

# 下载指定国家数据
def download_countryinfo(apiurl, appkey, origindir, countryid):
    data = {}
    data["appkey"] = appkey
    data["countryid"] = countryid
    data = urllib.parse.urlencode(data).encode('utf-8')
    result = urllib.request.urlopen(apiurl, data)
    jsonarr = json.loads(result.read())

    if jsonarr["status"] == 0:
        dict_obj = jsonarr["result"]
        country_name = dict_obj["name"]
        print(countryid, country_name)
        with open(origindir + country_name + ".json", "w") as f:
            json.dump(dict_obj, f, ensure_ascii=False)

# 下载全部国家数据
def download_countries(apiurl, appkey, origindir):
    # 总计 306 条
    for i in range(11, 15):
        download_countryinfo(apiurl, appkey, origindir, i)

    print("api数据获取完毕")
    print("*"*30)

# 保存国旗
def save_flag(flagsdir, flag_url, ename):
    urllib.request.urlretrieve(flag_url, filename=flagsdir+ename+".jpg")

# 下载全部国家国旗
def download_flags(resultdir, flagsdir, flagneturl):
    # 将文件
    for d in os.listdir(resultdir):
        ename = d[0:-5]
        with open(resultdir + d, "r") as f:
            dict_json = json.load(f)
            flag_url = dict_json["nationalflag"]
            # 如果 flag 结尾 url 不是 jpg, 则置为空
            if flag_url[-4:] != ".jpg":
                dict_json["nationalflag"] = None
            # 如果 flag 有图片, 则下载下来
            else:
                dict_json["nationalflag"] = flagneturl + ename + ".jpg"
                save_flag(flagsdir, flag_url, ename)
                print(ename + ".jpg saved!")
        # 保存 url进入 dict
        with open(resultdir + d, "w") as f:
            json.dump(dict_json, f, ensure_ascii=False)
